package org.dkakunsi.aplikasitoko.data.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.dkakunsi.aplikasitoko.data.entity.Kasir;
import org.dkakunsi.aplikasitoko.data.entity.Pembelian;
import org.dkakunsi.aplikasitoko.data.entity.Transaksi;
import org.dkakunsi.aplikasitoko.service.DataService;

public class Generator {

	private static int logNumber;
	private static int transaksiNumber;
	private static DataService ds;

	static {
		logNumber = 1;
		transaksiNumber = 1;
		ds = new DataService();
	}
	
	public static String getLogKode(Kasir kasir) {
		String partKode = getDateNow() + kasir.getKode();
	    String kode = partKode + getNumber("LOG");

	    try {
			while( ds.getInstance(kode, "PELAKU") != null) {
				logNumber++;
			    kode = partKode + getNumber("LOG");
			    System.out.println(kode);	    
			}
		} catch (ApplicationDataException e) {
			System.out.println(e.getMessage() + " @ Generator.getLogKode");
		}

	    return kode;
	}
	
	public static String getKodeTransaksi(Transaksi transaksi){
		String partKode = null;
		String kode = null;
		
		if(transaksi instanceof Pembelian){
			partKode = "BY" + getDateNow();
		} else { // transaksi instance of Penjualan
			partKode = "SL" + getDateNow();
		}
		
		kode = partKode + getNumber("TRANSAKSI");	
		try {
			while(ds.getInstance(kode, "TRANSAKSI") != null){
				transaksiNumber++;
				kode = partKode + getNumber("TRANSAKSI");
			}
		} catch (ApplicationDataException e) {
			System.out.println(e.getMessage() + " @ Generator.getTransaksiKode");
		}

		return kode;
	}
	
	private static String getNumber(String type){
		String numStr = null;
		
		if(type.equals("LOG")){
			numStr = "" + logNumber;
		} else if(type.equals("TRANSAKSI")){
			numStr = "" + transaksiNumber;
		}
		
		if(numStr.length() == 1) {
			return "0" + numStr;
		} else {
			return numStr;
		}
	}
	
	public static String getDateNow() {
	    Date now = new Date();
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd", Locale.getDefault());

	    return dateFormat.format(now);
	}
	
}
